package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.DtFinalResult;
import com.ruoyi.project.system.domain.DtQuery;
import com.ruoyi.project.system.domain.QueryVo;
import com.ruoyi.project.system.domain.dto.QueryDecision;
import com.ruoyi.project.system.domain.dto.TwoEleResult;
import com.ruoyi.project.system.domain.vo.CommandQuery;
import com.ruoyi.project.system.domain.vo.QueryRecord;
import com.ruoyi.project.system.mapper.DtFinalResultMapper;
import com.ruoyi.project.system.mapper.DtQueryMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.IDtFinalResultService;
import com.ruoyi.project.system.service.IDtQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.UUID;
import static com.ruoyi.common.utils.CryptoUtil.decrypt;
import static com.ruoyi.common.utils.CryptoUtil.encrypt;
import static com.ruoyi.common.utils.ServletUtils.getRequest;

/**
 * 查询列表Controller
 */
@RestController
@RequestMapping("/system/query")
public class DtQueryController extends BaseController {

    @Autowired
    private IDtQueryService dtQueryService;

    @Autowired
    private IDtFinalResultService iDtFinalResultService;

    @Autowired
    private DtQueryMapper dtQueryMapper;

    @Autowired
    private DtFinalResultMapper dtFinalResultMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 新增查询列表
     */
    @PostMapping
    @RepeatSubmit(message = "请勿短时间重复提交！")
    public AjaxResult add(@RequestBody @Validated DtQuery dtQuery) {
        dtQuery.setUserId(SecurityUtils.getUserId());
        TwoEleResult result = dtQueryService.verificationTwoEle(dtQuery);
        if (!result.isPass()) {
            return warn(result.getMsg());
        }
        dtQueryService.ordinaryAddQuery(dtQuery);
        Integer queryId = dtQuery.getQueryId();
        JSONObject result_ = (JSONObject) result.getInfo();
        dtQueryService.setQueryDecision(new QueryDecision(queryId, "address", result_.getString("address")));
        dtQueryService.setQueryDecision(new QueryDecision(queryId, "constellation", result_.getString("constellation")));

        String encrypt;
        try {
            encrypt = encrypt(dtQuery.getUserId() + "&&" + queryId);
            dtQueryMapper.updateDtQueryQt(queryId, encrypt);
        } catch (Exception e) {
            e.printStackTrace();
            return warn(e.getMessage());
        }
        if (dtQuery.getItems() != null && dtQuery.getItems().length > 0) {
            iDtFinalResultService.feeDeductions(dtQuery);
            return success(queryId).put("qt", encrypt);
        } else {
            return warn("请选择查询项目！");
        }
    }

    @Anonymous
    @PostMapping("/commandAdd")
    @RepeatSubmit(message = "请勿短时间重复提交！")
    public AjaxResult commandAdd(@RequestBody @Validated CommandQuery commandQuery) {
        Long userId = sysUserMapper.selectUserByCommand(commandQuery.getCommand());
        if (userId == null) {
            return warn("口令错误！");
        }
        DtQuery dtQuery = new DtQuery(commandQuery);
        dtQuery.setUserId(userId);
        TwoEleResult result = dtQueryService.verificationTwoEle(dtQuery);
        if (!result.isPass()) {
            return warn(result.getMsg());
        }
        dtQueryService.ordinaryAddQuery(dtQuery);
        Integer queryId = dtQuery.getQueryId();
        String encrypt;
        try {
            encrypt = encrypt(userId + "&&" + queryId);
            dtQueryMapper.updateDtQueryQt(queryId, encrypt);
        } catch (Exception e) {
            e.printStackTrace();
            return warn(e.getMessage());
        }
        return success(queryId).put("qt", encrypt);
    }

    /**
     * 查询
     */
    @Anonymous
    @GetMapping("/query")
    public AjaxResult query(@NotNull Integer queryId, @NotNull Integer productId) {
        HttpServletRequest hsr = getRequest();
        String qt = hsr.getHeader("Qt");
        if (StringUtils.isEmpty(qt)) {
            return warn("非法查询");
        }
        long decryptUserId;
        int decryptQueryId;
        try {
            String decrypt = decrypt(qt);
            String[] split = decrypt.split("&&");
            decryptUserId = Long.parseLong(split[0]);
            decryptQueryId = Integer.parseInt(split[1]);
        } catch (Exception e) {
            e.printStackTrace();
            return error("数据防护检测异常");
        }
        if (queryId.intValue() != decryptQueryId) {
            return warn("非法查询");
        }
        long userId = dtQueryMapper.selectUserIdByQueryId(queryId);
        if (userId != decryptUserId) {
            return warn("非法查询");
        }
        DtFinalResult dfr = dtFinalResultMapper.queryResult(userId, queryId, productId);
        if (dfr == null) {
            return new AjaxResult(300, "未付费");
        }
        return dtQueryService.fastQuery(dfr);
    }

    /**
     * 查询
     */

    @Anonymous
    @GetMapping("/feeQuery")
    @RepeatSubmit(message = "请勿短时间重复查询！")
    public AjaxResult feeQuery(@NotNull Integer queryId, @NotNull Integer productId) {
        String qt = getRequest().getHeader("Qt");
        if (StringUtils.isEmpty(qt)) {
            return warn("非法查询");
        }
        long decryptUserId;
        int decryptQueryId;
        try {
            String decrypt = decrypt(qt);
            String[] split = decrypt.split("&&");
            decryptUserId = Long.parseLong(split[0]);
            decryptQueryId = Integer.parseInt(split[1]);
        } catch (Exception e) {
            e.printStackTrace();
            return error("数据防护检测异常");
        }
        if (queryId.intValue() != decryptQueryId) {
            return warn("非法查询");
        }
        long userId = dtQueryMapper.selectUserIdByQueryId(queryId);
        if (userId != decryptUserId) {
            return warn("非法查询");
        }
        DtFinalResult dfr = iDtFinalResultService.feeDeduction(userId, productId, queryId);
        return dtQueryService.fastQuery(dfr);
    }

    @Anonymous
    @GetMapping("authCode/{queryId}")
    public String getAuthCode(@PathVariable("queryId") Integer queryId) {
        return dtQueryMapper.selectAuthCodeByQueryId(queryId);
    }

    @Anonymous
    @PutMapping("authCode/{queryId}")
    public String refreshAuthCode(DtQuery DtQuery) {
        String authCode = UUID.randomUUID().toString().substring(0, 8);
        DtQuery.setAuthCode(authCode);
        dtQueryMapper.updateDtQuery(DtQuery);
        return authCode;
    }

    /**
     * 查询查询列表列表
     */
    @PreAuthorize("@ss.hasPermi('system:list:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryVo queryVo) {
        if (!SecurityUtils.isAdmin()) {
            queryVo.setUserId(SecurityUtils.getUserId());
        }
        startPage();
        List<QueryRecord> list = dtQueryMapper.selectQueryList(queryVo);
        return getDataTable(dtQueryService.handlerQueryResult(list));
    }

    /**
     * 查询查询列表列表
     */
    @PreAuthorize("@ss.hasPermi('system:list:list')")
    @GetMapping("/listByParent")
    public TableDataInfo listByParent(QueryVo queryVo) {
        queryVo.setParent(SecurityUtils.getUserId());
        startPage();
        List<QueryRecord> list = dtQueryMapper.selectQueryList(queryVo);
        return getDataTable(dtQueryService.handlerQueryResult(list));
    }

    /**
     * 修改查询列表
     */
//    @PreAuthorize("@ss.hasPermi('system:list:edit')")
//    @Log(title = "查询列表", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody DtQuery DtQuery) {
//        return toAjax(dtQueryService.updateDtQuery(DtQuery));
//    }

    /**
     * 删除查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:list:remove')")
    @Log(title = "查询列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{queryIds}")
    public AjaxResult remove(@PathVariable Integer[] queryIds) {
        return toAjax(dtQueryService.deleteDtQueryByQueryIds(queryIds));
    }

}
